package com.shuqi.activity;

import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.shuqi.activity.viewport.CommonTitle;
import com.shuqi.activity.viewport.ToastDialog;
import com.shuqi.application.ShuqiApplication;
import com.shuqi.common.ControlHandler;
import com.shuqi.common.utils.Log4an;
import com.shuqi.controller.R;
import com.shuqi.interfaces.EventTypeConstants;
import com.shuqi.interfaces.IEventListener;
import com.shuqi.model.PayModel;
import com.shuqi.model.bean.PayFormInfo;
import com.shuqi.model.bean.PayItemInfo;
import com.shuqi.model.bean.PayTypeInfo;
import com.shuqi.model.net.listener.HttpRequestErrListener;

/**
 * 充值表单
 * 
 * @author chenwei
 * 
 */
public class PayFormActivity extends ActivityBase implements OnClickListener, IEventListener,
        HttpRequestErrListener {

    private final static String TAG = "PayFormActivity";

    private PayFormInfo mPayFormInfo;// 充值服务器返回
    private PayModel mPayModel;
    private ToastDialog mLoadingDialog;

    public final static int PAY_SUBMIT_SUCCESS = 1;
    public final static int PAY_SUBMIT = 2;
    public final static int PAY_SUBMIT_INIT = 3;
    public final static int NETERROR = 4;

    private CommonTitle mTitle;
    private TextView mTextCardName;// 标题卡类型
    private TextView mTextBalance;// 标题卡金额
    private Button mBtnFormSubmit;// 充值按钮
    private LinearLayout mLlHints;// 底部提示

    private PayTypeInfo mPayTypeInfo;// 上层穿来的支付类型
    private PayItemInfo mPayItemInfo;// 支付类型中的支付项
    private String mStrModeId;// 充值类型

    private EditText mEditCardNo;// 卡号
    private EditText mEditCardPwd;// 密码

    private TextView mTextCardNoError;// 卡号错误提示
    private TextView mTextPwdErro;// 密码错误提示

    // static 弱引用
    private ControlHandler handler = new ControlHandler(this) {

        public void handleMessage(Message msg) {
            Bundle data = msg.getData();

            switch (msg.what) {
                case PAY_SUBMIT_INIT:
                    activityLogicForward();
                    break;
                case PAY_SUBMIT_SUCCESS:
                    activityInitData();
                    break;
                case PAY_SUBMIT:
                    mPayModel.pay(data.getString("card_no"), data.getString("card_pw"), mStrModeId,
                            mPayTypeInfo.getTypeId(), mPayItemInfo.getItemId());
                    break;
                case NETERROR:
                    showLoadingDialog(false, true,
                            getResources().getString(R.string.payform_net_erro));
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_pay_form);

        mPayModel = new PayModel(this);
        mPayModel.addEventListener(this);

        handler.sendEmptyMessage(PAY_SUBMIT_INIT);
    }

    @Override
    public void onEvent(int event, Object data) {
        Log4an.d(TAG, "event:" + event + ",result:" + data);
        switch (event) {
            case EventTypeConstants.EVENT_SUCCESS:
                if (data != null) {
                    /*
                     * Message msg = new Message(); msg.what = PAY_SUBMIT_SUCCESS; Bundle d = new
                     * Bundle(); d.putSerializable("payFormInfo", (Serializable) data);
                     * msg.setData(d); handler.sendMessage(msg);
                     */
                    mPayFormInfo = (PayFormInfo) data;
                    handler.sendEmptyMessage(PAY_SUBMIT_SUCCESS);
                }
                break;
            default:
                handler.sendEmptyMessage(NETERROR);
                break;
        }
    }

    @Override
    public void activityLogicForward() {
        mLoadingDialog = new ToastDialog(this);

        /** title */
        mTitle = (CommonTitle) findViewById(R.id.title);
        mTitle.setLeftClickListener(this);

        mStrModeId = getIntent().getStringExtra("modeId");
        mPayTypeInfo = (PayTypeInfo) getIntent().getSerializableExtra("payTypeInfo");
        mPayItemInfo = (PayItemInfo) getIntent().getSerializableExtra("payItemInfo");

        mTextCardName = (TextView) findViewById(R.id.tv_card_name);
        mTextBalance = (TextView) findViewById(R.id.tv_balance);
        mEditCardNo = (EditText) findViewById(R.id.et_card_no);
        mEditCardPwd = (EditText) findViewById(R.id.et_card_pw);
        mTextCardNoError = (TextView) findViewById(R.id.tv_card_no_error);
        mTextPwdErro = (TextView) findViewById(R.id.tv_card_pw_error);
        mBtnFormSubmit = (Button) findViewById(R.id.btn_form_submit);
        mLlHints = (LinearLayout) findViewById(R.id.ll_hints);

        ((TextView) findViewById(R.id.tv_title)).setText(Html.fromHtml("当前选择为<font color=#14be7d>"
                + mPayTypeInfo.getCardName() + getResources().getString(R.string.payform_card)
                + "</font>" + "，充值金额为<font color=#14be7d>" + mPayItemInfo.getItemId()
                + getResources().getString(R.string.payform_balance) + "</font>"));
        mTextCardName.setText(mPayTypeInfo.getCardName()
                + getResources().getString(R.string.payform_card));
        mTextBalance.setText(mPayItemInfo.getItemId()
                + getResources().getString(R.string.payform_balance));
        mBtnFormSubmit.setOnClickListener(this);
        mEditCardNo.addTextChangedListener(watcher);
        mEditCardPwd.addTextChangedListener(watcherPw);

        List<String> hints = mPayTypeInfo.getHintsList();
        for (String hint : hints) {
            View view =
                    LayoutInflater.from(this).inflate(R.layout.pag_item, null,
                            false);
            ((TextView)view.findViewById(R.id.pay_desc)).setText(hint);
            mLlHints.addView(view);
        }
    }

    @Override
    public void activityInitData() {
        // PayFormInfo mPayFormInfo = (PayFormInfo) data.getSerializable("payFormInfo");

        if (mPayFormInfo != null && PayModel.NET_NEEDLOGIN.equals(mPayFormInfo.getCode())) {
            LoginActivity.openVerifyForResult(PayFormActivity.this, LoginActivity.LOGINTYPE_VERIFY);
            finish();
        } else if (mPayFormInfo != null && PayModel.NET_SUCCESS.equals(mPayFormInfo.getCode())
                && PayModel.NET_SUCCESS.equals(mPayFormInfo.getState())) {

            showLoadingDialog(false, true, getResources().getString(R.string.payform_submit_ok));

            ShuqiApplication.getApplicationHandler().postDelayed(new Runnable() {
                public void run() {
                    mLoadingDialog.dismiss();
                    Intent intent = new Intent(PayFormActivity.this, PayActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    ActivityManager.getInstance().startNextActivity(intent, PayFormActivity.this);
                }

            }, 1000);

        } else {
            showLoadingDialog(false, true, mPayFormInfo.getMessage());
            Log.d("liyizhe", "=========" + mPayFormInfo.getMessage());
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_left:
                ActivityManager.getInstance().finishActivity(this);
                break;
            case R.id.btn_form_submit:
                startSubmit();
                break;
        }
    }

    private void startSubmit() {
        String cardNo = mEditCardNo.getText().toString();
        String cardPw = mEditCardPwd.getText().toString();

        boolean isOK = isEnableFormat();// 查看格式
        if (!isOK) {
            return;
        }

        showLoadingDialog(true, false, getResources().getString(R.string.payform_submiting));

        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(this
                .getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

        Message msg = new Message();
        msg.what = PAY_SUBMIT;
        Bundle data = new Bundle();
        data.putString("card_no", cardNo);
        data.putString("card_pw", cardPw);
        msg.setData(data);
        handler.sendMessage(msg);
    }

    /**
     * 判断格式
     */
    private boolean isEnableFormat() {
        String cardNo = mEditCardNo.getText().toString();
        String cardPw = mEditCardPwd.getText().toString();

        if (("").equals(cardNo.trim())) {
            mTextCardNoError.setText(getResources().getString(R.string.payform_no_card));
            return false;
        } else {
            mTextCardNoError.setText("");
        }

        if (("").equals(cardPw.trim())) {
            mTextPwdErro.setText(getResources().getString(R.string.payform_no_pwd));
            return false;
        } else {
            mTextPwdErro.setText("");
        }

        return true;
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * 卡号监听
     */
    TextWatcher watcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() > 0 && mTextCardNoError.getVisibility() == View.VISIBLE) {
                // mTextCardNoError.setVisibility(View.GONE);
                mTextCardNoError.setText("");
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void afterTextChanged(Editable s) {}
    };

    /**
     * 密码监听
     */
    TextWatcher watcherPw = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() > 0 && mTextPwdErro.getVisibility() == View.VISIBLE) {
                // mTextPwdErro.setVisibility(View.GONE);
                mTextPwdErro.setText("");
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void afterTextChanged(Editable s) {}
    };

    /**
     * 显示底部加载
     */
    private void showLoadingDialog(boolean isLoading, boolean isSuccess, String showText) {
        if (isFinishing()) {
            return;
        }
        if (mLoadingDialog == null) {
            mLoadingDialog = new ToastDialog(this);
            mLoadingDialog.setDissmisOnClickOutSide(false);
        }
        if (isLoading) {
            mLoadingDialog.loading(showText);
            return;
        }
        mLoadingDialog.setDissmisOnClickOutSide(true);
        mLoadingDialog.show(isSuccess, showText);

    }

    @SuppressWarnings("unused")
    private void hideLoadingDialog() {
        Runnable r = new Runnable() {

            @Override
            public void run() {
                if (mLoadingDialog != null) {
                    mLoadingDialog.dismiss();
                }
            }
        };
        ShuqiApplication.getApplicationHandler().post(r);
    }

    @Override
    public void request_content_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_reponse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_io() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_parse_format() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_net_error() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_timeout() {
        // TODO Auto-generated method stub

    }

    @Override
    public void request_url() {
        // TODO Auto-generated method stub

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {

            ActivityManager.getInstance().finishActivity(this);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
